package org.rainbowinverted.charging.device.connect.ykc.server.util;

import cn.hutool.core.util.HexUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author hehuaiping
 */
public class Cp56Time2aUtils {
    private static final Integer DATA_LENGTH = 7;
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * Cp56Time2a转时间
     * @param hexCp56Time2a hexCp56Time2a
     * @return {@link LocalDateTime}
     */
    public static LocalDateTime hexCp56Time2aToTime(String hexCp56Time2a) {
        byte[] cp56Time2a = HexUtil.decodeHex(hexCp56Time2a);
        if (cp56Time2a.length != DATA_LENGTH) {
            throw new IllegalArgumentException("Invalid CP56Time2a format");
        }
        return LocalDateTime.parse(toDateString(cp56Time2a), DATE_TIME_FORMATTER);
    }


    /**
     * Cp56Time2a转时间字符串
     * @param bytes 字符数组
     * @return 时间字符串
     */
    public static String toDateString(byte[] bytes) {
        int milliseconds1 = bytes[0] < 0 ? 256 + bytes[0] : bytes[0];
        int milliseconds2 = bytes[1] < 0 ? 256 + bytes[1] : bytes[1];
        int milliseconds = milliseconds2 * 256 + milliseconds1 ;
        // 位于 0011 1111
        int minutes = bytes[2] & 0x3F;
        // 位于 0001 1111
        int hours = bytes[3] & 0x1F;
        // 位于 0001 1111
        int days = bytes[4] & 0x1F;
        // 位于 0000 1111
        int months = bytes[5] & 0x0F;
        // 位于 0111 1111
        int years = bytes[6] & 0x7F;
        return "20" + String.format("%02d", years) + "-" + String.format("%02d", months) + "-" + String.format("%02d", days) +
                " " + String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" +
                String.format("%02d", milliseconds / 1000);
    }

    /**
     * 时间转16进制字符串
     * @param time 时间
     * @return 16进制字符串
     */
    public static String date2HexStr(LocalDateTime time) {
        StringBuilder builder = new StringBuilder();
        String milliSecond = String.format("%04X", time.getSecond() * 1000);
        builder.append(milliSecond, 2, 4);
        builder.append(milliSecond, 0, 2);
        builder.append(String.format("%02X", time.getMinute() & 0x3F));
        builder.append(String.format("%02X", time.getHour() & 0x1F));
        int week = time.getDayOfWeek().getValue();
        builder.append(String.format("%02X", (week << 5) + time.getDayOfMonth() & 0x1F));
        builder.append(String.format("%02X", time.getMonthValue() & 0xf));
        builder.append(String.format("%02X", (time.getYear() - 2000) & 0x7f));
        return builder.toString();
    }

}